<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="队列,消息必达,消息幂等,消息落地,ack机制" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="背景最近工作中遇到送礼必达的业务，送礼必达的本质是队列消息必达，而队列消息必达的核心是： 1）消息ack 2）消息落地 下图展示一个可靠的消息从生产到消费的整个流程：  12345678910111）producer client 发送message，message中包含sequenceId（唯一id，可以是业务的订单id）；2）mq server收到消息，将消息落地存储；3）mq server回">
<meta name="keywords" content="队列,消息必达,消息幂等,消息落地,ack机制">
<meta property="og:type" content="article">
<meta property="og:title" content="消息必达">
<meta property="og:url" content="http://www.zhizus.com/2017-09-05-消息必达.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="背景最近工作中遇到送礼必达的业务，送礼必达的本质是队列消息必达，而队列消息必达的核心是： 1）消息ack 2）消息落地 下图展示一个可靠的消息从生产到消费的整个流程：  12345678910111）producer client 发送message，message中包含sequenceId（唯一id，可以是业务的订单id）；2）mq server收到消息，将消息落地存储；3）mq server回">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://www.zhizus.com/images/mq.png">
<meta property="og:updated_time" content="2018-07-30T00:44:48.217Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="消息必达">
<meta name="twitter:description" content="背景最近工作中遇到送礼必达的业务，送礼必达的本质是队列消息必达，而队列消息必达的核心是： 1）消息ack 2）消息落地 下图展示一个可靠的消息从生产到消费的整个流程：  12345678910111）producer client 发送message，message中包含sequenceId（唯一id，可以是业务的订单id）；2）mq server收到消息，将消息落地存储；3）mq server回">
<meta name="twitter:image" content="http://www.zhizus.com/images/mq.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2017-09-05-消息必达.html"/>





  <title> 消息必达 | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2017-09-05-消息必达.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                消息必达
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2017-09-05-消息必达.html" class="leancloud_visitors" data-flag-title="消息必达">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>最近工作中遇到送礼必达的业务，送礼必达的本质是队列消息必达，而队列消息必达的核心是：
1）<strong>消息ack</strong>
2）<strong>消息落地</strong>
下图展示一个可靠的消息从生产到消费的整个流程：
<span itemprop="image" itemscope="" itemtype="http://schema.org/ImageObject"><img itemprop="url image" src="/images/mq.png" class="full-image" alt="alt"><meta itemprop="width" content="auto"><meta itemprop="height" content="auto"></span></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>）producer client 发送message，message中包含sequenceId（唯一id，可以是业务的订单id）；</span><br><span class="line"><span class="number">2</span>）mq server收到消息，将消息落地存储；</span><br><span class="line"><span class="number">3</span>）mq server回复ack，告知client成功收到消息；</span><br><span class="line"><span class="comment">//如果 client未能收到ack</span></span><br><span class="line"><span class="comment">//a.mq Server没有收到消息，或者消息落地失败，这种情况，依赖producer client重发。producer client可以在发送消息之前将消息落地，收到ack再将消息删除（当然，大部分业务场景，没有收到ack，简单重试就好）</span></span><br><span class="line"><span class="comment">//b.mq Server收到消息，并且落地成功，第3步回复ack失败，或者回复成功，但producer client收ack消息，这种情况，producer也是要重发消息，mq Server会有重复消息</span></span><br><span class="line"></span><br><span class="line"><span class="number">4</span>）consume client 消费msg，（消费需要业务方保证消费业务幂等）；</span><br><span class="line"><span class="number">5</span>）consume client消费成功后，回复mq Server ack消息；</span><br><span class="line"><span class="number">6</span>）mq Server 收到consume client 发来的ack后，移动消息offset，并删除对应的落地消息。</span><br><span class="line"><span class="comment">// 第6步，删除对应的msg不一定需要，例如rocketmq或者kafka的存储机制就不需要，他们都特定的删除策略。</span></span><br></pre></td></tr></table></figure>
<ul>
<li>producer==&gt;broker必达（broker将消息落地之后再回复producer ack消息确认）</li>
<li>broker==&gt;consumer必达（consumer消费完消息在回复ack消息，broker收到ack消息后才能将对应消息删除）</li>
</ul>
<h2 id="消息的ack机制"><a href="#消息的ack机制" class="headerlink" title="消息的ack机制"></a>消息的ack机制</h2><p>消息的ack机制也就是消息的确认机制，是可靠消息的必要条件。可以粗暴的说，没有ack机制的消息系统一定不能保证消息必达。
   JMS API中约定了Client端可以使用四种ACK模式,在javax.jms.Session接口中:
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">AUTO_ACKNOWLEDGE = <span class="number">1</span>    <span class="comment">//自动确认</span></span><br><span class="line">CLIENT_ACKNOWLEDGE = <span class="number">2</span>   <span class="comment">// 客户端手动确认</span></span><br><span class="line">DUPS_OK_ACKNOWLEDGE = <span class="number">3</span>   <span class="comment">// 自动批量确认</span></span><br><span class="line">SESSION_TRANSACTED = <span class="number">0</span>    <span class="comment">//事务提交并确认</span></span><br></pre></td></tr></table></figure></p>
<p>ACK模式描述了Consumer与broker确认消息的方式(时机),比如当消息被Consumer接收之后,Consumer将在何时确认消息。对于broker而言，只有接收到ACK指令,才会认为消息被正确的接收或者处理成功了,通过ACK，可以在consumer（/producer）与Broker之间建立一种简单的“<code>担保</code>”机制.</p>
<p>  Client端指定了ACK模式,但是在Client与broker在交换ACK指令的时候,还需要告知ACK_TYPE,ACK_TYPE表示此确认指令的类型，不同的ACK_TYPE将传递着消息的状态，broker可以根据不同的ACK_TYPE对消息进行不同的操作。</p>
<p>  比如Consumer消费消息时出现异常,就需要向broker发送ACK指令,ACK_TYPE为”REDELIVERED_ACK_TYPE”,那么broker就会重新发送此消息。在JMS API中并没有定义ACT_TYPE,因为它通常是一种内部机制,并不会面向开发者。ActiveMQ中定义了如下几种ACK_TYPE(参看MessageAck类):</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">DELIVERED_ACK_TYPE = <span class="number">0</span>    <span class="comment">//消息"已接收"，但尚未处理结束</span></span><br><span class="line">STANDARD_ACK_TYPE = <span class="number">2</span>    <span class="comment">//"标准"类型,通常表示为消息"处理成功"，broker端可以删除消息了</span></span><br><span class="line">POSION_ACK_TYPE = <span class="number">1</span>    <span class="comment">//消息"错误",通常表示"抛弃"此消息，比如消息重发多次后，都无法正确处理时，消息将会被删除或者DLQ(死信队列)</span></span><br><span class="line">REDELIVERED_ACK_TYPE = <span class="number">3</span>    <span class="comment">//消息需"重发"，比如consumer处理消息时抛出了异常，broker稍后会重新发送此消息</span></span><br><span class="line">INDIVIDUAL_ACK_TYPE = <span class="number">4</span>    <span class="comment">//表示只确认"单条消息",无论在任何ACK_MODE下</span></span><br><span class="line">UNMATCHED_ACK_TYPE = <span class="number">5</span>    <span class="comment">//在Topic中，如果一条消息在转发给“订阅者”时，发现此消息不符合Selector过滤条件，那么此消息将 不会转发给订阅者，消息将会被存储引擎删除(相当于在Broker上确认了消息)。</span></span><br></pre></td></tr></table></figure>
<p>不同的消息队列对ack机制的实现不尽相同。比如activemq还实现了<code>optimizeACK</code>“延迟确认”的语义。但是，它们本质上都是通过ACK，在consumer（/producer）与Broker之间建立一种“<code>担保</code>”机制.</p>
<h3 id="消息传递语义（Message-delivery-semantics）"><a href="#消息传递语义（Message-delivery-semantics）" class="headerlink" title="消息传递语义（Message delivery semantics）"></a>消息传递语义（Message delivery semantics）</h3><p>消息传递语义：
“至多一次(<code>At Most Once</code>)”，消息发布完全依赖于底层TCP/IP网络。消息有可能丢失或重复。这一级别可应用于如下情景，如环境传感器数据，丢失一次读记录无所谓，因为很快下一次读记录就会产生。
“至少一次(<code>At Least Once</code>)”，确保消息到达，但消息重复有可能发生。
“只有一次(<code>Exactly Once</code>)”，确保消息到达且只到达一次。这一级别可用于如计费系统等场景，在计费系统中，消息丢失或重复可能会导致生成错误的费用。</p>
<p>消息必达实际上是消息传递语义的一个子集，至少一次和只有一次都可以保证消息必达。
但只有一次的实现成本较高，互联网的一般业务都是选择通过至少一次+业务方去重来满足只有一次的业务场景。</p>
<h3 id="消息幂等性"><a href="#消息幂等性" class="headerlink" title="消息幂等性"></a>消息幂等性</h3><p>消息系统中，消息<code>重复</code>和<code>丢失</code>两大恶魔，我们必须面对其中一个。
通过ack机制来保证消息不丢失，但是也引入了重复消息的问题，但是重复还可以去重，消息丢了，就无力回天。
可能有的消息系统会在server端去重，但这个代价也不小。大部分消息系统选择把消息去重的逻辑丢给了业务。因为业务方才是最容易理解需不需要去重，怎样去重最优。</p>
<p>而，<code>去重</code>也是消息幂等的一个解决方案之一。只要保证了消费逻辑的幂等性，也就解决了重复消息的问题。
关于幂等，请看<a href="http://www.zhizus.com/2017-08-28-%E5%B9%82%E7%AD%89.html">幂等</a></p>
<h2 id="消息落地"><a href="#消息落地" class="headerlink" title="消息落地"></a>消息落地</h2><p>消息落地就是将消息持久化而已，比较简单，但是对于不同的队列对消息落地的实现不同，也是非常值得学习研究的。</p>
<p>消息落地是消息可靠性的基本保障，只有消息落地了，才有资格谈消息可靠，但是消息落地并不代表消息一定可靠，永不丢失。</p>
<h3 id="消息可靠性"><a href="#消息可靠性" class="headerlink" title="消息可靠性"></a>消息可靠性</h3><p>不同的mq对消息可靠性有不同的保障，有的对性能要求较高，对可靠性要求较低，可能将消息落地到内存。
下面是RocketMq的消息可靠性：</p>
<blockquote>
<p>(1)Broker正常关闭
(2)Broker异常Crash
(3)OS Crash
(4)机器掉电，但是能立即恢复供电情况。
(5)机器无法开机（可能是cpu、主板、内存等关键设备损坏）
(6)磁盘设备损坏。</p>
</blockquote>
<p>(1)、(2)、(3)、(4)四种情况都属于硬件资源可立即恢复情况，RocketMQ在这四种情况下能保证消息不丢，或者丢失少量数据（依赖刷盘方式是同步还是异步）。</p>
<p>(5)、(6)属于单点故障，且无法恢复，一旦发生，在此单点上的消息全部丢失。RocketMQ在这两种情况下，通过异步复制，可保证99%的消息不丢，但是仍然会有极少量的消息可能丢失。通过同步双写技术可以完全避免单点，同步双写势必会影响性能，适合对消息可靠性要求极高的场合，例如与Money相关的应用。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>消息必达是队列的很重的的特性，也是很基础的特性，选择队列的首要考虑条件。一个无法保证消息必达的队列，使用时一定要慎重，会给业务带来很多不必要的麻烦。</p>
<h2 id="参考文章"><a href="#参考文章" class="headerlink" title="参考文章"></a>参考文章</h2><p><a href="http://wely.iteye.com/blog/2363981" target="_blank" rel="noopener">http://wely.iteye.com/blog/2363981</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017-09-04-流量拷贝利器tcpcopy.html" rel="next" title="流量拷贝利器tcpcopy">
                <i class="fa fa-chevron-left"></i> 流量拷贝利器tcpcopy
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-09-08-浅谈事务.html" rel="prev" title="浅谈事务">
                浅谈事务 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#消息的ack机制"><span class="nav-number">2.</span> <span class="nav-text">消息的ack机制</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#消息传递语义（Message-delivery-semantics）"><span class="nav-number">2.1.</span> <span class="nav-text">消息传递语义（Message delivery semantics）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#消息幂等性"><span class="nav-number">2.2.</span> <span class="nav-text">消息幂等性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#消息落地"><span class="nav-number">3.</span> <span class="nav-text">消息落地</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#消息可靠性"><span class="nav-number">3.1.</span> <span class="nav-text">消息可靠性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文章"><span class="nav-number">5.</span> <span class="nav-text">参考文章</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
